package rahmath.sharif.docrypt;

import java.util.ArrayList;
import java.util.Collections;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.entity.Data;
import rahmath.sharif.docrypt.entity.Vault;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class DatasActivity extends ListActivity implements DocryptConstants {


	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_datas);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		final Vault vault = DocryptUtil.getVaultFromSD(getIntent().getExtras()
				.getString(VAULT_FILE_NAME));
		Log.d("Vault Object", vault.getDatas().keySet().toString());
		ArrayList<String> datasList = new ArrayList<String>(vault.getDatas()
				.keySet());
		Collections.sort(datasList);
		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item_vault,
				datasList));
		final ListView listView = getListView();
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long length) {
				Intent intentManageData = new Intent(DatasActivity.this,
						ManageDataActivity.class);
				intentManageData.putExtra(DATA_KEY,
						listView.getItemAtPosition(position).toString());
				intentManageData.putExtra(VAULT_FILE_NAME,
						vault.getVaultFileName());
				intentManageData.putExtra(VAULT_PASSWORD, getIntent()
						.getExtras().getString(VAULT_PASSWORD));
				startActivity(intentManageData);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_datas, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.createData:
			LayoutInflater infalter = LayoutInflater.from(DatasActivity.this);
			final View dataNameView = infalter.inflate(
					R.layout.alert_dialog_name, null);
			final EditText editTextDataName = ((EditText) dataNameView
					.findViewById(R.id.editTextAlertName));
			editTextDataName
					.setOnFocusChangeListener(new OnFocusChangeListener() {
						public void onFocusChange(View v, boolean hasFocus) {
							editTextDataName.post(new Runnable() {
								public void run() {
									InputMethodManager inputMethodManager = (InputMethodManager) DatasActivity.this
											.getSystemService(Context.INPUT_METHOD_SERVICE);
									inputMethodManager.showSoftInput(
											editTextDataName,
											InputMethodManager.SHOW_IMPLICIT);
								}
							});
						}
					});
			editTextDataName.requestFocus();
			final DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					String dataNameEntered = editTextDataName.getText()
							.toString().trim();
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Vault vault = DocryptUtil.getVaultFromSD(getIntent()
								.getExtras().getString(VAULT_FILE_NAME));
						if (vault.getDatas().containsKey(dataNameEntered)) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataNameExists),
									Toast.LENGTH_SHORT).show();
							return;
						}
						Data data = new Data(dataNameEntered);
						vault.getDatas().put(dataNameEntered, data);
						boolean success = DocryptUtil.putVaultToSD(vault);
						if (success) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataSaveSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent intentManageData = new Intent(
									DatasActivity.this,
									ManageDataActivity.class);
							intentManageData.putExtra(
									VAULT_FILE_NAME,
									getIntent().getExtras().getString(
											VAULT_FILE_NAME));
							intentManageData
									.putExtra(DATA_KEY, dataNameEntered);
							intentManageData.putExtra(
									VAULT_PASSWORD,
									getIntent().getExtras().getString(
											VAULT_PASSWORD));
							startActivity(intentManageData);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataSaveFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};

			new AlertDialog.Builder(DatasActivity.this).setCancelable(false)
					.setTitle("Create Data").setMessage("Enter Data Name.")
					.setPositiveButton("Create", dialogListener)
					.setNegativeButton("Cancel", dialogListener)
					.setView(dataNameView).show();
			return true;
		case R.id.lockVault:
			Intent vaultsIntent = new Intent(this, VaultsActivity.class);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(vaultsIntent);
			return true;
		case R.id.deleteVault:
			final Vault vaultDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteVault = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						boolean success = DocryptUtil
								.deleteVaultFromSD(vaultDel);
						if (success) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							// No need of intent with "clear top flag" Just
							// finish;
							finish();
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(DatasActivity.this).setCancelable(false)
					.setTitle("Confirm Delete!")
					.setMessage("Vault : " + vaultDel.getName())
					.setPositiveButton("Delete", confirmDialogDeleteVault)
					.setNegativeButton("Cancel", confirmDialogDeleteVault)
					.show();
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
